package servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import tools.Utility;

import beans.CartBean;
import beans.ErrorBean;
import beans.OrderBean;
import beans.OrderList;
import beans.UserBean;

public class ProfileDispatcher extends HttpServlet {

	private static String pageShop = null;
	private static String pageProfile = null;
	private static String pageLogin = null;
	private static String pageSignout = null;
	private static String pagePassword = null;
	private static String pageRegister = null;
	private static String pageError = null;
	private static String pageAdmin = null;
	private static String pageMyOrders = null;
	private static String pageMyOrderDetail = null;

	// page, request, session, application variables
	private static final String ERROR = "errorMessage";
	private static final String USER_PROFILE = "user_profile";

	/**
	 * Constructor of the object.
	 */
	public ProfileDispatcher() {
		super();
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init(ServletConfig config) throws ServletException {
		super.init(config);

		// get pages path
		pageShop = config.getInitParameter("PAGE_SHOP");
		pageProfile = config.getInitParameter("PAGE_MYPROFILE");
		pageLogin = config.getInitParameter("PAGE_LOGIN");
		pageSignout = config.getInitParameter("PAGE_SIGNOUT");
		pagePassword = config.getInitParameter("PAGE_PASSWORD");
		pageRegister = config.getInitParameter("PAGE_REGISTER");
		pageError = config.getInitParameter("PAGE_ERROR");
		pageAdmin = config.getInitParameter("PAGE_ADMIN");
		pageMyOrders = config.getInitParameter("PAGE_MYORDERS");
		pageMyOrderDetail = config.getInitParameter("PAGE_MYORDERDETAIL");
	}

	private void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String action = request.getParameter("action");

		HttpSession session = request.getSession();
		UserBean userProfile = (UserBean) session.getAttribute(USER_PROFILE);

		if (action == null) {
			action = "show";
		}

		// show myProfile.jsp
		if (action.equals("show")) {
			if (userProfile == null) {
				request.getRequestDispatcher(pageLogin).forward(request,
						response);
			} else {
				request.getRequestDispatcher(pageProfile).forward(request,
						response);
			}
		} else if (action.equals("update")) {
			String email = request.getParameter("email");
			String name = request.getParameter("name");
			String address = request.getParameter("address");
			String city = request.getParameter("city");
			String country = request.getParameter("country");
			String phone = request.getParameter("phone");

			UserBean user = new UserBean();
			user.setEmail(email.trim());
			user.setName(name);
			user.setAddress(address);
			user.setCity(city);
			user.setCountry(country);
			user.setPhone(phone);

			if (user.updateProfilebyEmail()) {
				// set message
				user.setMessage("Update Sucessfully");
				// update the userProfile in the session
				session.setAttribute(USER_PROFILE, user);
				// forward to the main shop page
				request.getRequestDispatcher(pageProfile).forward(request,
						response);
			} else {
				// set message
				user.setMessage("Update unsucessfully");
				// forward to the main shop page
				request.getRequestDispatcher(pageProfile).forward(request,
						response);
			}
		} else if (action.equals("password")) {
			String category = request.getParameter("category");
			if (category == null) {
				// just show this page
				if (userProfile == null) {
					request.getRequestDispatcher(pageLogin).forward(request,
							response);
				} else {
					request.getRequestDispatcher(pagePassword).forward(request,
							response);
				}
			} else if (category.equals("update")) {
				// update password
				String oldPassword = request.getParameter("oldpassword");
				String newPassword = request.getParameter("newpassword");
				String newPassword2 = request.getParameter("newpassword2");

				UserBean user = (UserBean) (request.getSession()
						.getAttribute(USER_PROFILE));

				if (user == null) {
					request.getRequestDispatcher(pageLogin).forward(request,
							response);
					return;
				}

				// check parameters
				if (!oldPassword.trim().equals(user.getPassword().trim())) {
					// wrong old password
					user.setMessage("Old password is incorrect");
				} else if (oldPassword.equals("") || newPassword.equals("")
						|| newPassword2.equals("")) {
					// empty input
					user.setMessage("All the fields are required");
				} else if (!newPassword.trim().equals(newPassword2.trim())) {
					// two new passwords do not match each other
					user.setMessage("The two new password do not match");
				} else {
					// All right
					user.setPassword(newPassword.trim());
					if (user.updatePasswordbyEmail()) {
						// set message
						user.setMessage("Password Changed Sucessfully");
					} else {
						// set message
						user.setMessage("Password Changed unsucessfully");
					}
				}

				// put the userProfile into the session
				session.setAttribute(USER_PROFILE, user);
				// forward to the main shop page
				request.getRequestDispatcher(pagePassword).forward(request,
						response);
			}
		} else if (action.equals("signout")) {
			if (session.getAttribute(USER_PROFILE) != null) {
				session.removeAttribute(USER_PROFILE);
			}
			session.invalidate();
			response.sendRedirect(("/OnlineShop" + pageSignout));
		} else if (action.equals("orderdetail")) {
			String orderid = request.getParameter("orderid");
			try {
				OrderBean order = new OrderBean();
				order.setOrderbyID(Integer.parseInt(orderid));
				request.setAttribute("MYORDERDETAIL", order);

				CartBean cart = Utility
						.ConvertProductString_to_ProductList(order
								.getProductString());
				request.setAttribute("MYORDERPRODUCTS", cart);

				request.getRequestDispatcher(pageMyOrderDetail).forward(
						request, response);

			} catch (Exception e) {

			}

		} else if (action.equals("order")) {
			OrderList orders = new OrderList();

			UserBean user = (UserBean) session.getAttribute(USER_PROFILE);
			if (user != null) {
				orders.setOrdersByUserID(user.getId());
				request.setAttribute("MYORDERS", orders);
				request.getRequestDispatcher(pageMyOrders).forward(request,
						response);
			} else {
				request.getRequestDispatcher(pageLogin).forward(request,
						response);
			}
		} else if (action.equals("register")) {
			UserBean user = new UserBean();
			ErrorBean error = new ErrorBean();
			
			// get parameters from request
			String name = request.getParameter("name");
			String password = request.getParameter("password");
			String re_password = request.getParameter("re_password");
			String address = request.getParameter("address");
			String city = request.getParameter("city");
			String country = request.getParameter("country");
			String email = request.getParameter("email");
			String phone = request.getParameter("phone");

			// check the parameters
			if (name == null || password == null || re_password == null
					|| address == null || city == null || country == null
					|| email == null || phone == null || name.equals("")
					|| password.equals("") || re_password.equals("")
					|| address.equals("") || city.equals("")
					|| country.equals("") || email.equals("")
					|| phone.equals("")) {			
				error.setMessage("All fields are required!");
				
				request.setAttribute("ERROR", error);
				request.getRequestDispatcher(pageRegister).forward(request, response);
				return;
			}
			
			if(!password.equals(re_password)){
				error.setMessage("Passwords are not same!");
				request.setAttribute("ERROR", error);
				request.getRequestDispatcher(pageRegister).forward(request, response);
				return;
			}
			
			if(user.isUsed(email)){
				error.setMessage("The Email address is registered!");
				request.setAttribute("ERROR", error);
				request.getRequestDispatcher(pageRegister).forward(request, response);
				return;
			}
			
			//set bean
			user.setName(name);
			user.setRole(0);
			user.setAddress(address);
			user.setCity(city);
			user.setCountry(country);
			user.setEmail(email);
			user.setPassword(password);
			user.setPhone(phone);
			
			if(!user.insert()){
				error.setMessage("Some errors occur in the process of register!");
				request.setAttribute("ERROR", error);
				request.getRequestDispatcher(pageRegister).forward(request, response);
			} else {
				error.setMessage("Register Sucessfully!");
				request.setAttribute("ERROR", error);
				request.getRequestDispatcher(pageLogin).forward(request, response);
			}			
		} else if (action.equals("login")) {
			String email = request.getParameter("username");
			String password = request.getParameter("password");

			if (email.equals("") || password.equals("")) {
				String errorMessage = "Your username(Email) or password is empty, please <a href=\"/OnlineShop/login.jsp\">try</a> again.";
				gotoErrorPage(request, response, errorMessage);
			}

			UserBean user = new UserBean();
			user.setEmail(email.trim());

			if (user.setProfilebyEmail() && user.isValid(password.trim())) {
				// put the userProfile into the session
				session.setAttribute(USER_PROFILE, user);
				// forward to the main shop page
				if (user.getRole() == 0) {
					String pageUrl = request.getParameter("redirect");
					if (pageUrl != null && !pageUrl.equals("")) {
						request.getRequestDispatcher("/" + pageUrl + ".jsp")
								.forward(request, response);
					} else {
						request.getRequestDispatcher(pageShop).forward(request,
								response);
					}
				} else {
					request.getRequestDispatcher(pageAdmin).forward(request,
							response);
				}

			} else {
				String errorMessage = "Your username(Email) or password is incorrect, please <a href=\"/OnlineShop/login.jsp\">try</a> again.";
				gotoErrorPage(request, response, errorMessage);
			}
		}
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		processRequest(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		processRequest(request, response);
	}

	private void gotoErrorPage(HttpServletRequest request,
			HttpServletResponse response, String errorMessage)
			throws ServletException, IOException {
		ErrorBean error = new ErrorBean();
		error.setMessage(errorMessage);
		request.setAttribute(ERROR, error);
		request.getRequestDispatcher(pageError).forward(request, response);
	}
}
